package cn.elead.it.sso.sample.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.elead.it.sso.core.constant.GlobalVariable;
import cn.elead.it.sso.core.filter.SsoWebFilter;
import cn.elead.it.sso.core.util.JedisUtil;
import cn.elead.it.sso.properties.SsoProperties;

/**
 * sso配置
 * 
 * @author luopeng
 *
 */
@Configuration
@EnableConfigurationProperties(SsoProperties.class)
public class SsoConfig implements InitializingBean, DisposableBean {

	@Autowired
	private SsoProperties ssoProperties;

	@Bean
	public FilterRegistrationBean<SsoWebFilter> SsoFilterRegistration() {

		FilterRegistrationBean<SsoWebFilter> registration = new FilterRegistrationBean<SsoWebFilter>();

		registration.setName("SsoWebFilter");
		registration.setOrder(1);
		registration.addUrlPatterns("/*");
		registration.setFilter(new SsoWebFilter());
		registration.addInitParameter(GlobalVariable.SSO_SERVER, ssoProperties.getServer());
		registration.addInitParameter(GlobalVariable.SSO_LOGOUT_PATH, ssoProperties.getLogoutUrl());
		registration.addInitParameter(GlobalVariable.SSO_CLIENTID, ssoProperties.getClient().getClientId());
		registration.addInitParameter(GlobalVariable.SSO_CLIENTSECRET, ssoProperties.getClient().getClientSecret());
		registration.addInitParameter(GlobalVariable.SSO_EXCLUDED_PATHS, ssoProperties.getExcludedPaths());

		return registration;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		JedisUtil.init(ssoProperties.getRedis().getAddress());
	}

	@Override
	public void destroy() throws Exception {
		JedisUtil.close();
	}

}
